package com.yanboo.processor;

import java.util.concurrent.ThreadFactory;

public final class ThreadUtil {

    /**
     * Creates a new Thread from the given factory and prefixes it's name with a prefix and sets the daemon flag.
     *
     * @param threadFactory the thread factory.
     * @param runnable      The runnable to thread.
     * @param prefix        the thread name prefix
     * @param daemon        marks this thread as a daemon thread
     * @return constructed thread, or {@code null} if the request to create a thread is rejected
     */
    static Thread newThread(final ThreadFactory threadFactory, final Runnable runnable, final String prefix, final boolean daemon) {
        final Thread thread = threadFactory.newThread(runnable);
        if (thread == null) {
            throw new IllegalStateException(String.format("The ThreadFactory %s cound not construct a thread for '%s'", threadFactory, prefix));
        }
        thread.setName(prefix + thread.getName());
        thread.setDaemon(daemon);
        return thread;
    }

}
